package com.ujson.chat.server.handler;

import com.ujson.base.common.task.AsyncTask;
import com.ujson.base.common.utils.LogUtil;
import com.ujson.chat.common.handler.AbstractHandler;
import com.ujson.chat.common.proto.MessageProto;
import com.ujson.chat.server.processor.ChatProcessor;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <h3>ujson-parent</h3>
 * <p>聊天转发处理器</p>
 *
 * @author JerryLiu  a1031757312@gmail.com
 * @version 1.0
 * @date 2021-11-23 21:41
 */
@Slf4j
@Service
@ChannelHandler.Sharable
public class ChatRedirectHandler extends AbstractHandler {
    @Autowired
    private ChatProcessor chatProcessor;

    public MessageProto.MessageType getMessageType() {
        return MessageProto.MessageType.MESSAGE_REQUEST;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (!super.messageTypeCheck(ctx, msg)) {
            return ;
        }

        MessageProto.MessageRequest message = ((MessageProto.Message) msg).getMessageRequest();
        // start business handle
        LogUtil.info(log, "chat msg read, from: "+message.getFrom()+", to: "+message.getTo()+", content: " + message.getContent());

        AsyncTask.addTask(() -> {
            return chatProcessor.messageRedirect(ctx, message);
        }).thenApplyAsync(mmsg -> {
            ctx.channel().writeAndFlush(mmsg);
            return null;
        });

    }
}
